class MagazineController < ApplicationController
  def list
   allVersion = Version.find_by_sql('select * from versions order by id desc')
   list = []
    allVersion.each do |v|
    single = {'coverImg' => v[:imgName],'time' => v[:time],'theme' => v[:theme],'description' => v[:description],'id' =>v[:id],'sourceName' => v[:sourceName]}
    list.push(single)
    end
    render :json =>{'list' => list }
  end
  def info
    id = params[:id]
    if id
      version = Version.find_by_id(id)
    else
      version = Version.find_by_sql('select * from versions order by id desc')[0]
    end

     render :json =>{"coverImg" => version[:imgName],"time" => version[:time],"theme" => version[:theme],"description"=>version[:description],"id" =>version[:id]}
  end
  def edit
    id=params[:id]
    @editVersion=Version.find_by_id(id)
  end
  def add

  end
  def new
    time = params[:time]
    theme = params[:theme]
    description = params[:description]
    image = params[:imgName]
    source = params[:source]

    File.open("#{Rails.root}/public/covers/#{image.original_filename}","wb") do |img|
      img.write(image.read)
    end

    File.open("#{Rails.root}/public/sources/#{source.original_filename}","wb") do |s|
      s.write(source.read)
    end
    Version.new_version(time,theme,image.original_filename,description,source.original_filename)
    redirect_to "/magazine/manage"
  end
  def update
    time = params[:time]
    theme = params[:theme]
    description = params[:description]
    imgName = params[:imgName]
    id = params[:id]
    Version.update_version(time,theme,imgName,description,id)
    redirect_to "/magazine/manage"
  end
  def manage
    @allVersion = Version.find_by_sql('select * from versions order by id desc')
  end
  def delete
    id=params[:id].to_i
    v=Version.find_by_id(id)
    # File.delete("#{Rails.root}/public/covers/#{v[:imgName]}")
    File.delete("#{Rails.root}/public/sources/#{v[:sourceName]}")
    Version.delete(id)
    redirect_to "/magazine/manage"
  end
end
